<template>
  <div>
    <van-nav-bar
        title="中国人民公安大学图书馆选座"/>
    <van-cell-group title="请选择楼层和时间">
      <van-overlay :show="overlay" >
        <van-loading style="display: flex;align-items: center;justify-content: center;height: 100%;" >
          座位加载中...
        </van-loading>
      </van-overlay>
      <van-field
          readonly
          clickable
          label="楼层"
          :value="floor"
          placeholder="选择楼层"
          @click="showFloorPicker = true"
      />

      <van-popup v-model="showFloorPicker" round position="bottom">
        <van-picker
            show-toolbar
            :columns="floorNumberList"
            @cancel="showFloorPicker = false"
            @confirm="onFloorConfirm"
        />
      </van-popup>
      <van-field
          readonly
          clickable
          label="时间"
          :value="time"
          placeholder="选择时间"
          @click="showTimePicker = true"
      />

      <van-popup v-model="showTimePicker" round position="bottom">
        <van-datetime-picker
            show-toolbar
            @cancel="showTimePicker = false"
            v-model="currentTime"
            type="time"
            title="选择时间"
            @confirm="onTimeConfirm"
            :min-hour="7"
            :max-hour="22"
            :filter="timeFilter"

        />
      </van-popup>
    </van-cell-group>
    <van-cell-group title="请选择座位">

      <div class="seat-select">
        <van-cell v-for="y in yy" :key="y" style="padding: 0" class="seat-select">
          <van-row type="flex" justify="center" >
            <van-icon v-for="x in xx"
                      @click="seatSelect(x,y)"
                      class="iconfont" class-prefix='icon'
                      size="28px"
                      :name="seatAvailable"
                      :class="`seat-item-${x+'-'+y}`"
                      :key="x">
            </van-icon>
          </van-row>
        </van-cell>
      </div>
    </van-cell-group>
    <van-cell>
      <van-button id="confirmBtn" @click="confirmBtnClick" :disabled="disableConfirm" type="primary" size="large">立即预定</van-button>
    </van-cell>
    <div style="height: 50px"></div>
    <Tabbar></Tabbar>
  </div>
</template>

<script>
import {listAvailableSeats, listByLibraryId,selectSeat} from '@/api/seat'
import {formatDate} from '@/utils/date'
import {Dialog, Notify} from "vant";
import Tabbar from "@/components/Tabbar";
export default {
  components: {Tabbar},
  created() {
    this.overlay = true
    listByLibraryId(this.libraryId).then(response=>{
      if(response.data.code===401)
        this.$router.push("login")
      for(let i = 0;i<response.data.length;i++){
        this.floorList.push(response.data[i])
        this.floorNumberList.push(response.data[i].floorNumber+"楼")
      }
    });
    listAvailableSeats(this.availableSeatsParam).then(response => {
      this.seats = response.data;
      this.seats.forEach(function(seat) {
        let node = document.querySelector(`.seat-item-${seat.number}`);
        node.className = "iconfont icon icon-kexuanzuowei seat-item-"+seat.number;
      })
      this.overlay = false
    });
  },
  name: "Home",
  data(){
    return {
      overlay:true,
      currentTime:new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getMinutes(),
      libraryId:{
        id:1
      },
      disableConfirm:true,
      xx:10,
      yy:20,
      floor:"3楼",
      floorNumberList: [],
      time:new Date().getHours()+":"+new Date().getMinutes(),
      showFloorPicker: false,
      showTimePicker:false,
      floorList: [],
      column:20,
      availableSeatsParam:{
        start:formatDate(new Date(),"yyyy-MM-dd hh:mm:ss").toString(),
        end:formatDate(new Date(),"yyyy-MM-dd hh:mm:ss").toString()
            .replace(/..:..:../,"22:00:00"),
        floorId:1

      },
      seatAvailable:"yixuanzuowei",
      selectedSeatList:[],
      selectedSeatIdList:[],
      seats:[],
      seatSelectionParam:{
        end: "",
        seatId: 0,
        start: "",
      }
    };
  },
  methods: {

    confirmBtnClick(){
      Dialog.confirm({
        title: '确认选座',
        message: '是否选择座位:['+this.selectedSeatList+"]",
      }).then(() => {
            for(let i=0;i<this.seats.length;i++){
              for (let j=0;j<this.selectedSeatList.length;j++){
                if(this.selectedSeatList[j]===this.seats[i].number){
                  this.selectedSeatIdList.push(this.seats[i].id)
                  this.seatSelectionParam.end = this.availableSeatsParam.end
                  this.seatSelectionParam.start = this.availableSeatsParam.start
                  this.seatSelectionParam.seatId = this.seats[i].id;
                  selectSeat(this.seatSelectionParam).then(response => {
                    if(response!=null&&response.data!==0){
                      let node = document.querySelector(`.seat-item-${this.selectedSeatList[j]}`);
                      node.className = "iconfont icon icon-yixuanzuowei seat-item-"+this.selectedSeatList[j];
                      Dialog.alert({
                        title: '选座成功',
                        message: '请及时到位',
                      }).then(() => {

                      });
                    }
                  });
                }
              }
            }
          })
          .catch(() => {

          });



    },
    onFloorConfirm(value) {
      this.overlay = true
      this.floor = value;
      this.showFloorPicker = false;
      for (let i=0;i<this.floorList.length;i++){
        if(this.floorList[i].floorNumber.toString()===value.substr(0,1)){
          this.xx = this.floorList[i].y;
          this.yy = this.floorList[i].x;
        }
      }
      for(let y=1;y<=this.yy;y++){
        for(let x=1;x<=this.xx;x++){
          let node = document.querySelector(`.seat-item-${x+"-"+y}`);
          if(node!=null){
            node.className = "iconfont icon icon-yixuanzuowei seat-item-"+x+"-"+y;
          }
        }
      }
      for(let i = 0 ; i<this.floorList.length;i++){
        if(value.substr(0,1)===this.floorList[i].floorNumber.toString()){
          this.availableSeatsParam.floorId=this.floorList[i].id;
        }
      }
      listAvailableSeats(this.availableSeatsParam).then(response => {

        this.seats = response.data;
        this.seats.forEach(function(seat) {
          let node = document.querySelector(`.seat-item-${seat.number}`);
          node.className = "iconfont icon icon-kexuanzuowei seat-item-"+seat.number;
        })
        this.overlay = false
      });
    },
    onTimeConfirm(time) {
      this.time = time;
      const now = new Date();
      let nowTimeInt;
      if(now.getMinutes()>9){
        nowTimeInt =  parseInt(now.getHours()+""+now.getMinutes())
      }else {
        nowTimeInt = parseInt(now.getHours()+"0"+now.getMinutes())
      }
      if(parseInt(time.toString().replace(":",""))
          <nowTimeInt){
        Notify({ type: 'danger', message: '不能选择现在之前的时间' });
      }else {
        this.availableSeatsParam.start = formatDate(now,"yyyy-MM-dd hh:mm:ss").toString()
            .replace(/..:..:/,time+":")
        this.availableSeatsParam.end = formatDate(now,"yyyy-MM-dd hh:mm:ss").toString()
            .replace(/..:..:../,"22:00:00")

        this.showTimePicker = false;
      }
    },
    seatSelect(x,y){
      const node = document.querySelector(`.seat-item-${x+'-'+y}`);
      if(node.className.indexOf("kexuanzuowei")!==-1){
        if(this.selectedSeatList.length>=2){
          Notify({ type: 'danger', message: '选择座位不能超过2个' });
        }else {
          node.className = "iconfont icon icon-woxuanzuowei seat-item-"+x+'-'+y
          this.selectedSeatList.push(x+'-'+y)
        }
      }else if(node.className.indexOf("woxuanzuowei")!==-1){
        node.className = "iconfont icon icon-kexuanzuowei seat-item-"+x+'-'+y
        for(let i=0;i<this.selectedSeatList.length;i++){
          if(this.selectedSeatList[i]===x+'-'+y){
            this.selectedSeatList.splice(i,1)
          }
        }
      }
      this.disableConfirm = this.selectedSeatList.length <= 0;
    },
    timeFilter(type, options){
      if(type==='hour'){
        return options.filter((option) => option >= new Date().getHours());
      }
      return options;
    }
  },
}

</script>

<style scoped>
.seat-select{
  text-align:center;
}

</style>
